<template>
	<transition name="remark">
		<div class="wrap" v-show="isShow">
			<aside class="back" @click="back">back</aside>

			<v-header :seller="seller"></v-header>
			<section class="wrapper" ref="foodList">
				<ul class="list_content">
					<li class="food_list" v-for="(food ,index) in selectFoods" :key="index">
						<aside class="food_icon">
							<img :src="food.icon" alt="">
						</aside>

						<aside class="text_content">
							<span class="name">{{food.name}}</span>
							<aside class="option_list">
								<span class="option" v-for="(item,index) in food.options_text" :key="index">{{item}}</span>
							</aside>
						</aside>
						<div class="cartControl-wrapper">
							<cart-control :food="food" @increment="incrementTotal($event, food)"></cart-control>
						</div>
						<!--<div class="count"><span>X{{ food.qty }}</span></div>-->
						<div class="price"><span>${{food.price * 100 * food.qty/100}}</span></div>
					</li>
					<div class="takeOption">
						<label class="mint-radiolist-title"><span style="color:red;">*</span> takeOption</label>
						<mt-radio v-model="takeOption" :options='takeOptions'></mt-radio>
					</div>
					<div class="payment">
						<label class="mint-radiolist-title"><span style="color:red;">*</span> paymentMethod</label>
						<mt-radio :options='paymentOptions' v-model="paymentMethod"></mt-radio>
					</div>
					<div class="creditcard" v-show="paymentMethod === 'creditcard'">
						<label class="mint-radiolist-title">creditCardInfo</label>
						<mt-field label='Holder' v-model="holder"></mt-field>
						<mt-field label='Number' v-model="number" type='number'></mt-field>
						<mt-field label='cvv2' v-model="cvv2" type='number'></mt-field>
						<mt-field label='Expire' v-model="expire" @focus.native.capture='selectExpire'></mt-field>
					</div>
					<label class="mint-radiolist-title">Others</label>
					<div class="tip">
						<mt-field label='TipAccount' v-model="tipAmount" type='number' @blur.native.capture='formatTipAccount'></mt-field>
					</div>
					<div class="message">
						<mt-field label='Message' type='textarea' v-model="comments"></mt-field>
					</div>
					<label class="mint-radiolist-title">BILL</label>
					<div class="">
						<mt-cell title="SUBTOTAL" :value='totalPrice | format-dollar '></mt-cell>
						<mt-cell title="TAX" :value='tax | format-dollar '></mt-cell>
						<mt-cell title="TOTAL" :value='total | format-dollar'></mt-cell>
					</div>
				</ul>

			</section>

			<section class="checkout">
				<aside class="price">
					<!--<span>${{totalPrice}}</span>-->
				</aside>
				<aside class="confirm" :class="{disabled:!confirmStatus}" @click="checkout">
					Confirm Order
				</aside>
			</section>
			<mt-datetime-picker ref="picker" type='date' :startDate='now' cancelText='cancel' confirmText='confirm' v-model="dataPickerValue" @confirm='handleConfirm'></mt-datetime-picker>
		</div>

	</transition>
</template>
<script type="text/ecmascript-6">
// import axios from 'axios'
import BScroll from "better-scroll";
import header from "../header/header.vue";
import { Field, Radio, Toast, DatetimePicker, Cell } from "mint-ui";
import { verifyCardNumber } from "../../common/js/util.js";
import cartControl from "../cartControl/cartControl.vue";

//  const ERR_OK = 0;
export default {
  props: {
    seller: {
      type: Object
    },
    isShow: {
      type: Boolean
    }
  },
  data() {
    return {
      curIndex: 0,
      scroll: null,
      test: "选项1",
      optionIndex: [],
      input: "",
      takeOption: "",
      takeOptions: [
        {
          label: "dine-in",
          value: "dine-in"
        },
        {
          label: "take-out",
          value: "take-out"
        }
      ],
      paymentOptions: [
        {
          label: "cash",
          value: "cash"
        },
        {
          label: "creditcard",
          value: "creditcard"
        }
      ],
      paymentMethod: "",
      tipAmount: "",
      comments: "",
      holder: "",
      number: "",
      cvv2: "",
      expire: "",
      dataPickerValue: ""
    };
  },
  created() {},
  mounted() {},
  computed: {
    selectFoods() {
      return this.$store.getters.selectedFoods;
    },
    totalPrice() {
      let total = 0;
      this.selectFoods.forEach(food => {
        total += food.price * 100 * food.qty;
      });
      return total / 100;
    },
    tax() {
      return Number(
        this.totalPrice * this.$store.state.seller.tax_rate / 100
      ).toFixed(2);
    },
    total() {
      return Number(this.tax) + Number(this.totalPrice);
    },
    now() {
      let date = new Date();
      return date;
    },
    confirmStatus() {
      if (!this.takeOption) {
        // this.showToast('Please select takeOption')
        return false;
      }
      if (!this.paymentMethod) {
        // this.showToast('Please select paymentMethod')
        return false;
      }
      if (
        this.paymentMethod === "creditcard" &&
        (!this.number || !this.cvv2 || !this.holder || !this.expire)
      ) {
        // this.showToast('Please fill out your creditcard\' info')
        return false;
      }
      return true;
    }
  },
  watch: {
    selectFoods() {
      this.setScroll();
    },
    isShow(val) {
      if (val) {
        this.setScroll();
      }
    },
    paymentMethod() {
      this.setScroll();
    }
  },
  methods: {
    setScroll() {
		//   this.$nextTick(() => {
		//     //$refs绑定元素
		//     if (!this.scroll) {
		//       this.scroll = new BScroll(this.$refs.foodList, {
		//         //开启点击事件 默认为false
		//         click: true
		//       });
		//       // console.log(this.scroll)
		//     } else if (!this.$refs.foodList) {
		//       return;
		//     } else {
		//       this.scroll.refresh();
		//     }
		//   });
    },
    incrementTotal(target, good) {
      this.$store.commit("setTarget", target);
      //this.$refs.shopCart.drop(target);
    },
    back() {
      this.reset();
      this.$store.commit("setShow", {
        target: "order",
        status: false
      });
    },
    showToast(message) {
      Toast({
        message: message,
        duration: 2000
      });
    },
    verifyFormInfo() {
      if (!this.takeOption) {
        this.showToast("Please select takeOption");
        return false;
      }
      if (!this.paymentMethod) {
        this.showToast("Please select paymentMethod");
        return false;
      }
      if (
        this.paymentMethod === "creditcard" &&
        (!this.number || !this.cvv2 || !this.holder || !this.expire)
      ) {
        this.showToast("Please fill out your creditcard' info");
        return false;
      }

      if (
        this.paymentMethod === "creditcard" &&
        !verifyCardNumber(this.number)
      ) {
        this.showToast("Please enter correct creditcard number");
        return false;
      }
    },
    selectExpire() {
      this.$refs.picker.open();
    },
    //提交接口 http://www.fetail.com/api2/checkout/confirm/order
    checkout() {
      if (!this.verifyFormInfo()) {
        return;
      }
      console.log(verifyCardNumber(this.number));
      // console.log(this.formatNumber)
      console.log("------checkout--------");
      let products = this.selectFoods.map(item => {
        let options = item.options.map(v => {
          let option_id = v.option_id;
          let temp = "options[" + option_id + "]";
          return {
            [option_id]: item[temp]
          };
        });
        return {
          productId: item.id,
          qty: item.qty,
          note: item.note,
          options: options
        };
      });
      console.log(typeof this.number);
      let data = {
        paymentMethod: this.paymentMethod,
        paymentTime: this.paymentMethod === "cash" ? "later" : "now",
        takeOption: this.takeOption,
        tipAmount: this.tipAmount,
        comments: this.comments,
        products: products
      };

      if (this.paymentMethod === "creditcard") {
        let expireArr = this.expire.split("/");
        let expire =
          (expireArr[1].length < 2 ? "0" + expireArr[1] : expireArr[1]) +
          expireArr[0].slice(2);
        data.creditCardInfo = {
          holder: this.holder,
          number: this.number,
          cvv2: this.cvv2,
          expire: expire
        };
      }
      console.log(this);
      this.$store.dispatch("commit", {
        data,
        reset: this.reset
      });
      // this.reset()
      // this.$http.post('/api2/checkout/confirm/order',data)
      //   .then(res => {
      //     if(res.data.code === 1){
      //       this.showToast('success')
      //       this.$store.commit("setShow", { target: "order", status: false });
      //       this.$store.commit('clearSelectFoods')
      //     }else{
      //       this.showToast(res.data.message)
      //     }
      //   })
      console.log("---data----", data);
    },
    handleConfirm(value) {
      console.log(value);
      let date = new Date(value);
      this.expire = date.toLocaleDateString();
    },
    reset() {
      this.takeOption = "";
      this.paymentMethod = "";
      this.number = "";
      this.holder = "";
      this.cvv2 = "";
      this.expire = "";
      this.tipAmount = "";
      this.comments = "";
    },
    formatTipAccount() {
      this.tipAmount = Number(this.tipAmount).toFixed(1);
    }
  },
  components: {
    vHeader: header,
    "mt-field": Field,
    "mt-radio": Radio,
    "mt-datetime-picker": DatetimePicker,
    cartControl,
    "mt-cell": Cell
  }
};
</script>

<style lang="less" scoped rel="stylesheet/stylus">
.wrap {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 100;
  background: white;
  & * {
    box-sizing: border-box;
  }
}

.fixed {
  width: 100%;
  position: fixed !important;
}

.back {
  position: fixed;
  top: 0.2rem;
  right: 0.3rem;
  padding: 0.3rem 0.3rem;
  box-shadow: 0 0 0.06rem #ccc;
  border-radius: 0.1rem;
  color: white;
  z-index: 999;
}

.wrapper {
  position: absolute;
  top: 1.25rem;
  height: calc(100% - 2.6rem);
  width: 100%;
  overflow-y: scroll;
  -webkit-overflow-scrolling:touch
}

.list_content {
  padding: 0.2rem 0.3rem;
  .food_list {
    width: 100%;
    height: 1rem;
    margin-bottom: 0.3rem;
    box-shadow: 0 0.02rem 0.03rem #ccc;
    padding-right: 0.2rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 0.1rem;
    overflow: hidden;
    .text_content {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      padding: 0 0.1rem;
      height: 100%;
      .name {
        display: block;
      }
      .option_list {
        .option {
          font-size: 0.03rem;
          padding: 0.05rem 0.1rem;
          border-radius: 0.1rem;
          margin-right: 0.1rem;
          box-shadow: 0 0 1px #ccc;
        }
      }
    }
    .food_icon {
      width: 1rem;
      height: 1rem;
      border-radius: 0.02rem;
      overflow: hidden;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .count {
      text-align: left;
      width: 0.5rem;
    }
    .price {
      width: 0.8rem;
      text-align: right;
    }
    .cartControl-wrapper {
      width: 2rem;
    }
  }
}

@height: 1rem;
.checkout {
  position: fixed;
  display: flex;
  bottom: 0;
  left: 0;
  width: 100%;
  height: @height;
  box-shadow: 0 -3px 3px #cccccc;
  .price {
    padding: 0 0.5rem;
    line-height: @height;
    color: white;
    flex: 1;
    background: #141d27;
    span {
      font-size: 0.35rem;
    }
  }
  .confirm {
    text-align: center;
    width: 3.1rem;
    height: @height;
    line-height: @height;
    background: #00b43c;
    font-size: 0.35rem;
    color: white;

    &.disabled {
      background-color: #2b333b !important;
    }
  }
}

.remark-enter-active,
.remark-leave-active {
  transition: all 0.5s ease-in-out;
}

.remark-enter,
.remark-leave-active {
  transform: translate3d(0, 100%, 0);
}
</style>